﻿using hyjx.comm.Exceptions;
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;

namespace hyjx.comm
{
    /// <summary>
    /// 通信帮助程序
    /// </summary>
    public class CommunicateHelper
    {
        /// <summary>
        /// Ping
        /// </summary>
        /// <param name="target">目标</param>
        /// <param name="data">数据</param>
        /// <param name="timeOutMilliseconds">回复消息的最大毫秒数</param>
        /// <exception cref="CommunicatePingException">Ping 异常</exception>
        /// <returns>是否 Ping 通</returns>
        public bool Ping(string target, string data = "1", int timeOutMilliseconds = 120)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions
            {
                DontFragment = true
            };

            byte[] buffer = Encoding.ASCII.GetBytes(data);
            try
            {
                PingReply reply = pingSender.Send(target, timeOutMilliseconds, buffer, options);
                if (reply.Status == IPStatus.Success)
                    return true;
                else
                    return false;
            }
            catch (PingException ex)
            {
                throw new CommunicatePingException(nameof(PingException), ex);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                throw new CommunicatePingException(nameof(ArgumentOutOfRangeException), ex);
            }
            catch (ArgumentNullException ex)
            {
                throw new CommunicatePingException(nameof(ArgumentNullException), ex);
            }
            catch (ArgumentException ex)
            {
                throw new CommunicatePingException(nameof(ArgumentException), ex);
            }
            catch(InvalidOperationException ex)
            {
                throw new CommunicatePingException(nameof(InvalidOperationException), ex);
            }
            catch(NotSupportedException ex)
            {
                throw new CommunicatePingException(nameof(NotSupportedException), ex);
            }
            catch (Exception ex)
            {
                throw new CommunicatePingException(nameof(Exception), ex);
            }
        }
    }
}
